from decimal import Decimal, InvalidOperation

from django import template
from django.conf import settings
from babel.numbers import format_currency

register = template.Library()


@register.simple_tag(takes_context=True)
def product_price(context, product, user):
    if not user or not user.is_authenticated():
        return ''

    if product.is_group:
        price = product.min_variant_vendor_price(user)
        return '<span> <i>Desde</i> %s </span>' % currency(price)
    else:
        price = product.vendor_price(user)
        return '<span>%s</span>' % currency(price)

def currency(value):
    """
    Format decimal value as currency
    """
    try:
        value = Decimal(value)
    except (TypeError, InvalidOperation):
        return u""
    # Using Babel's currency formatting
    # http://packages.python.org/Babel/api/babel.numbers-module.html#format_currency
    kwargs = {
        'currency': settings.OSCAR_DEFAULT_CURRENCY,
        'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)}
    locale = getattr(settings, 'OSCAR_CURRENCY_LOCALE', None)
    if locale:
        kwargs['locale'] = locale
    return format_currency(value, **kwargs)
